package com.leonardo.persistenceme.model.persistancehandlers;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;

import com.leonardo.persistenceme.Class2Handler;

public class VectorPersistenceHandler extends PersistenceHandler {

	public void persist(Object obj, DataOutputStream stream) throws IOException {
		if(obj == null) {
			stream.writeInt(0);
			return;
		}
		Vector vector = (Vector) obj;
		stream.writeInt(vector.size());
		for(int i = 0; i < vector.size(); i++) {
			Object elem = vector.elementAt(i);
			stream.writeUTF(elem.getClass().getName());
			PersistenceHandler handler = Class2Handler.getHandlerOrDefault(elem.getClass());
			handler.persist(elem, stream);
		}
	}

	public Object recover(DataInputStream stream) throws IOException {
		int length = stream.readInt();
		if(length == 0)
			return null;
		Vector vector = new Vector(length);
		for(int i = 0; i < length; i++) {
			String className = stream.readUTF();
			try {
				Class clazz = Class.forName(className);
				PersistenceHandler handler = Class2Handler.getHandlerOrDefault(clazz);
				vector.addElement(handler.recover(stream));
			} catch (ClassNotFoundException e) {
				throw new RuntimeException("Class " + className + " not found to restore Vector. " + e.getMessage());
			}
		}
		return vector;
	}

}
